﻿using Client.Constant;
using Client.Enum;
using Client.Framework.Event;
using Client.Framework.Message;
using Client.Framework.Socket;
using Client.Message.Request;
using Client.Message.Response;
using Client.Model;
using Client.Service;
using Client.View;
using Client.View.CommonView;
using Client.View.UserView;
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Client.ViewModel.UserViewModel
{
    public class UserListViewModel : BindableBase
    {
        public UserListViewModel()
        {
            MsgEventSubscribe();
            Init();
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        private void Init()
        {
            AddUserCommand = new DelegateCommand(AddUser);
            RefreshUserListCommand = new DelegateCommand(RefreshUserList);
            PrePageCommand = new DelegateCommand(PrePage);
            NextPageCommand = new DelegateCommand(NextPage);
            EditUserCommand = new DelegateCommand<ViewUser>(EditUser);
            DeleteUserCommand = new DelegateCommand<ViewUser>(DeleteUser);
            SelectedOrgCommand = new DelegateCommand<ViewOrg>(SelectedOrg);
            SearchCommand = new DelegateCommand(Search);
            ResetCommand = new DelegateCommand(Reset);

            OrgTreeUserControl = new OrgTreeNoBtn()
            {
                DataContext = this
            };
            OrgTree = OrgService.Instance().OrgTree;

            UserEditWindow = new UserEdit();

            HasPrePage = false;
            HasNextPage = false;

            InitUsers();
        }

        public void InitUsers()
        {
            GetUsers();
        }

        /// <summary>
        /// 消息事件订阅
        /// </summary>
        private void MsgEventSubscribe()
        {
            OrgService.Instance().SubscribeRefreshOrgTreeEvent(RefreshOrgTree);
            MessageEventPublisher.SubscribeEvent(MessageId.USER_LIST, UsersResp);
            MessageEventPublisher.SubscribeEvent(MessageId.OPT_RESP, OptResp);
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        private List<ViewUser> users;
        public List<ViewUser> Users
        {
            get { return users; }
            set
            {
                users = value;
                RaisePropertyChanged("Users");
            }
        }


        /// <summary>
        /// 新增编辑页面
        /// </summary>
        public UserEdit UserEditWindow { get; private set; }

        /// <summary>
        /// 当前页码
        /// </summary>
        private int currentPage = 1;

        public int CurrentPage
        {
            get { return currentPage; }
            set { currentPage = value; RaisePropertyChanged("CurrentPage"); }
        }

        /// <summary>
        /// 每页条数
        /// </summary>
        private readonly int LIMIT = 10;

        /// <summary>
        /// 是否有上一页
        /// </summary>
        private bool hasPrePage;

        public bool HasPrePage
        {
            get { return hasPrePage; }
            set
            {
                hasPrePage = value;
                RaisePropertyChanged("HasPrePage");
            }
        }



        /// <summary>
        /// 是否有下一页
        /// </summary>
        private bool hasNextPage;

        public bool HasNextPage
        {
            get { return hasNextPage; }
            set
            {
                hasNextPage = value;
                RaisePropertyChanged("HasNextPage");
            }
        }


        /// <summary>
        /// 新增角色
        /// </summary>
        public DelegateCommand AddUserCommand { get; private set; }
        public void AddUser()
        {
            UserEditWindow.BindParentContextAndEntity(this);
            UserEditWindow.ShowDialog();
        }

        /// <summary>
        /// 刷新角色列表
        /// </summary>
        public DelegateCommand RefreshUserListCommand { get; private set; }
        public void RefreshUserList()
        {
            GetUsers();
        }

        /// <summary>
        /// 上一页
        /// </summary>
        public DelegateCommand PrePageCommand { get; private set; }
        public void PrePage()
        {
            if (hasPrePage)
            {
                CurrentPage--;
                GetUsers();
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        public DelegateCommand NextPageCommand { get; private set; }
        public void NextPage()
        {
            if (hasNextPage)
            {
                CurrentPage++;
                GetUsers();
            }
        }

        /// <summary>
        /// 编辑角色信息
        /// </summary>
        public DelegateCommand<ViewUser> EditUserCommand { get; private set; }
        public void EditUser(ViewUser user)
        {
            UserEditWindow.BindParentContextAndEntity(this, user);
            UserEditWindow.ShowDialog();
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        public DelegateCommand<ViewUser> DeleteUserCommand { get; private set; }
        private int deleteUserId;
        public void DeleteUser(ViewUser user)
        {
            this.deleteUserId = user.ID;
            CancelConfirmTip tip = new CancelConfirmTip()
            {
                Message = { Text = $"确定删除用户{user.LoginName}吗？" }
            };
            DialogHost.Show(tip, "MainPanel", CloseTip);
        }
        public void CloseTip(object sender, DialogClosingEventArgs eventArgs)
        {
            if (string.Equals(eventArgs.Parameter, "Cancel")) return;
            DeleteUserReq msg = new DeleteUserReq(MessageId.DELETE_USER)
            {
                ID = this.deleteUserId
            };
            ApplicationClient.Instance().Send(msg);
        }
        private void OptResp(ResponseBaseMessage message)
        {
            if (message is OperationResp msg)
            {
                if (msg.Code == 200 && msg.OptType == (int)OptType.DELETE_USER)
                {
                    GetUsers();
                }
            }
        }



        private ViewUser condition = new ViewUser() {Status = 0};

        public ViewUser Condition
        {
            get { return condition; }
            set
            {
                condition = value;
                RaisePropertyChanged("Condition");
            }
        }


        /// <summary>
        /// 获取用户列表
        /// </summary>
        public void GetUsers()
        {
            UserListReq msg = new UserListReq(MessageId.REQUEST_USER_LIST)
            {
                Page = CurrentPage,
                Limit = LIMIT,
                Condition = Condition
            };
            ApplicationClient.Instance().Send(msg);
        }


        /// <summary>
        /// 列表信息返回
        /// </summary>
        /// <param name="message">返回的消息</param>
        private void UsersResp(ResponseBaseMessage message)
        {
            if (message is UserListResp msg)
            {
                Users = msg.Users;
                HasPrePage = CurrentPage > 1;
                HasNextPage = CurrentPage < (int)Math.Ceiling((double)msg.Count / LIMIT);
            }
        }




        public OrgTreeNoBtn OrgTreeUserControl { get; set; }

        private void RefreshOrgTree(List<ViewOrg> orgTree)
        {
            OrgTree = orgTree;
        }

        private List<ViewOrg> orgTree;

        public List<ViewOrg> OrgTree
        {
            get { return orgTree; }
            set
            {
                orgTree = value;
                RaisePropertyChanged("OrgTree");
            }
        }


        public DelegateCommand<ViewOrg> SelectedOrgCommand { get; set; }
        private void SelectedOrg(ViewOrg org)
        {
            if (org == null) return;
            Condition.OrgId = org.ID;
            GetUsers();
        }


        public DelegateCommand SearchCommand { get; set; }
        private void Search()
        {
            GetUsers();
        }

        public DelegateCommand ResetCommand { get; set; }
        private void Reset()
        {
            OrgTreeUserControl.ResetSelectedStatus();
            Condition.OrgId = 0;
            Condition.LoginName = string.Empty;
            Condition.Status = 0;
            GetUsers();
        }


    }
}
